﻿using ConsoleApplication.WebAPI;
using Kingdee.BOS;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Util;
using Kingdee.BOS.WebApi.Client;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NS
{
    [HotUpdate]
    [Description("物料打开时从新品规则表加载图片信息")]
    public class LoadPicture : AbstractDynamicFormPlugIn
    {
        public override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            var FNumber=this.View.Model.GetValue("FNumber");
            K3CloudApiClient client = new K3CloudApiClient("http://127.0.0.1/k3cloud/");

            var loginResult = client.ValidateLogin("646c7773bfad99", "Administrator", "ns@123456", 2052);

            var resultType = JObject.Parse(loginResult)["LoginResultType"].Value<int>();

            if (resultType == 1)
            {
                object[] paramInfo = new object[]

                {

                    "{\"FormId\":\"k0848cf0964ee43ef96f485f22bbd3d77\","+// 采购订单formid

                    "\"TopRowCount\":0,"+// 最多允许查询的数量，0或者不要此属性表示不限制

                    "\"Limit\":10,"+// 分页取数每页允许获取的数据，最大不能超过2000

                    "\"StartRow\":0,"+// 分页取数开始行索引，从0开始，例如每页10行数据，第2页开始是10，第3页开始是20

                    "\"FilterString\":\"F_WNEG_Text1='"+FNumber+"'\","+// 过滤条件

                    "\"OrderString\":\"FID ASC\"," + // 排序条件     

                     "\"FieldKeys\":\"FNumber,F_WNEG_Image1\"}"// 获取采购订单数据参数，内码，供应商id，物料id,物料编码，物料名称

                };


                //调用查询接口

                List<List<object>> ret = client.Execute<List<List<object>>>("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery", paramInfo);
                if (ret != null && ret.Count > 0)

                {

                    string s = ret[0][1] as string;



                    Kingdee.BOS.JSON.JSONArray array = new Kingdee.BOS.JSON.JSONArray();

                    array = SerializatonUtil.DeserializeFromBase64<Kingdee.BOS.JSON.JSONArray>(s);



                    for (int i = 0; i < array.Count; i++)

                    {

                        string serverFileName = Convert.ToString(((Kingdee.BOS.JSON.JSONObject)array[i])["ServerFileName"]);

                        string fileName = Convert.ToString(((Kingdee.BOS.JSON.JSONObject)array[i])["FileName"]);

                        byte[] fileContent = ((Kingdee.BOS.JSON.JSONObject)array[i])["FileContent"] as byte[];



                        string path = "D:\\tmp\\" + fileName;



                        File.WriteAllBytes(path, fileContent);





                    }

                }
            }
        }
    }
}
